package dal

import (
	"git-hawk/internal/logic/models"
)

func GetProject() ([]models.Project, error) {
	ret, err := DB.Query("select * from project")
	if err != nil {
		return nil, err
	}
	var cs []models.Project
	for ret.Next() {
		var cat models.Project
		_ = ret.Scan(&cat.Id, &cat.Name, &cat.Path, &cat.Remote_name, &cat.Remote_path, &cat.Status)
		cs = append(cs, cat)
	}
	return cs, nil
}

func SaveProject(project *models.Project) error {
	ret, err := DB.Exec("insert into project (name,path) values (?,?)", project.Name, project.Path)
	if err != nil {
		return err
	}
	lastInsertId, err := ret.LastInsertId()
	if err != nil {
		return err
	}
	project.Id = int(lastInsertId)
	return nil
}

func UpdateProject(project *models.Project) error {
	ret, err := DB.Exec("update project set name=?,path=? where id=?", project.Name, project.Path, project.Id)
	if err != nil {
		return err
	}
	lastInsertId, err := ret.LastInsertId()
	if err != nil {
		return err
	}
	project.Id = int(lastInsertId)
	return nil
}

func DeleteProject(id int) error {
	ret, err := DB.Exec("delete from project where id=?", id)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected()
	if err != nil {
		return err
	}
	return nil
}
